<template>
    <div>
        <!-- 搜索 -->
        <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
            <el-form-item label="姓名">
                <el-input v-model="queryInfo.name" placeholder="请输入搜索姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="queryInfo.phone" placeholder="请输入电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="queryInfo.status" placeholder="全部" clearable>
                    <el-option label="启用" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loadUsers">查询</el-button>
                <el-button type="success" @click="handleAdd">添加</el-button>
                <el-button type="danger" @click="removeBatch">批量删除</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="users" style="width: 100%" border stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="70"></el-table-column>
            <el-table-column label="序号" type="index" width="70"></el-table-column>
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="电话" prop="phone"></el-table-column>
            <el-table-column label="地址" prop="address"></el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1"
                        @change="modifyStatus(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 20, 50]" :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <!-- 用户对话框 -->
        <el-dialog :title="title" :visible.sync="formDialogVisible" :close-on-click-modal="false"
            @close="handleDialogClose">
            <el-form :model="user" :rules="rules" ref="userFormRef">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="user.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="user.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="user.address" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="formDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addOrUpdate">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

export default {
    data() {
        return {
            // 用户数据
            users: [],
            // 查询条件
            queryInfo: {
                pageNum: 1,
                pageSize: 5,
                name: '',
                phone: '',
                status: ''
            },
            // 总条数
            total: 0,
            // 添加对话框是否可见
            formDialogVisible: false,
            // 表单数据
            user: {
                name: '',
                phone: '',
                address: ''
            },
            // 表单校验规则
            rules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' },
                ]
            },
            // 对话框的标题
            title: '',
            // 多选的用户
            multipleSelection: []
        }
    },
    methods: {
        // 显示编辑对话框
        async handleEdit(id) {
            // 根据id查询用户信息
            const { data: res } = await this.$http.get(`/users/query/${id}`)
            this.user = res.data

            // 显示对话框
            this.title = '编辑用户'
            this.formDialogVisible = true
        },
        // 删除用户
        handleDelete(id) {
            this.$confirm('确定要删除该用户吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 向后端发送请求，删除对应的用户
                const { data: res } = await this.$http.delete(`/users/remove/${id}`)
                if (res.status !== 200) {
                    return this.$message.error('删除用户失败！');
                }
                // 弹出提示
                this.$message.success('删除用户成功！');
                // 重新加载用户数据
                this.loadUsers()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 加载用户数据
        async loadUsers() {
            var { data: res } = await this.$http.get('/users/queryByPage', {
                params: this.queryInfo
            })
            this.users = res.data.records
            this.total = res.data.total
        },
        // 监听页大小的改变
        handleSizeChange(val) {
            this.queryInfo.pageSize = val
            this.loadUsers()
        },
        // 监听页码的改变
        handleCurrentChange(val) {
            this.queryInfo.pageNum = val
            this.loadUsers()
        },
        // 修改用户状态
        async modifyStatus(user) {
            const { data: res } = await this.$http.put(`/users/modifyStatus/${user.id}/${user.status}`)
            if (res.status !== 200) {
                return this.$message.error('修改状态失败')
            }
            this.$message.success('修改状态成功')
        },
        // 添加/更新用户
        addOrUpdate() {
            // 先判断表单校验是否成功
            this.$refs.userFormRef.validate(async valid => {
                // 如果校验失败，则退出
                if (!valid) {
                    return
                }

                /**
                 * 判断是添加还是修改操作！！
                 */
                if (this.title === '添加用户') {
                    // 如果校验通过，则向后端发送请求
                    const { data: res } = await this.$http.post('/users/add', this.user)
                    if (res.status !== 200) {
                        return this.$message.error('添加用户失败')
                    }
                    // 提示消息
                    this.$message.success('添加用户成功')
                } else {
                    const { data: res } = await this.$http.put('/users/modify', this.user)
                    if (res.status !== 200) {
                        return this.$message.error('修改用户失败')
                    }
                    // 提示消息
                    this.$message.success('修改用户成功')
                }

                // 重新加载数据
                this.loadUsers()
                // 关闭对话框
                this.formDialogVisible = false
            })
        },
        // 监听对话框的关闭
        handleDialogClose() {
            this.$refs.userFormRef.resetFields() // 重置表单
        },
        // 显示添加对话框
        handleAdd() {
            this.title = '添加用户'
            this.formDialogVisible = true
        },
        // 监听多选框的选中状态
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 批量删除
        async removeBatch() {
            this.$confirm('确定要删除用户吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 获取要删除的用户id
                var ids = []
                this.multipleSelection.forEach(item => {
                    ids.push(item.id)
                })

                const { data: res } = await this.$http.delete('/users/removeBatch', {
                    data: ids
                })
                if (res.status !== 200) {
                    return this.$message.error('批量删除失败')
                }
                this.$message.success('批量删除成功')
                this.loadUsers()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    },
    created() {
        this.loadUsers();
    }
}
</script>

<style></style>